<template>
	<view class="video-page">
		<!-- 顶部导航栏 -->
		<TopNav 
			:activeTab="activeTab" 
			@tabChange="handleTabChange"
			@menuClick="handleMenuClick"
			@searchClick="handleSearchClick"
		/>
		
		<!-- 左侧抽屉 -->
		<SideDrawer
			ref="sideDrawerRef"
			:user="user"
			@login="handleLogin"
			@logout="handleLogout"
		/>
		
		<!-- 视频列表 -->
		<swiper 
			class="video-swiper" 
			:current="currentIndex"
			:vertical="true"
			:circular="false"
			:duration="300"
			@change="handleSwiperChange"
			:style="{ height: screenHeight + 'px' }"
		>
			<swiper-item 
				v-for="(video, index) in videoList" 
				:key="video.id"
				class="swiper-item"
			>
                <VideoItem 
					:videoData="video"
					:isActive="currentIndex === index"
					:screenHeight="screenHeight"
					@play="handleVideoPlay"
					@pause="handleVideoPause"
                    @statementClick="handleStatementClick"
				/>
				
				<!-- 右侧交互按钮 -->
				<ActionButtons 
					:videoData="video"
					@follow="handleFollow"
					@like="handleLike"
					@comment="handleComment"
					@favorite="handleFavorite"
					@share="handleShare"
				/>
			</swiper-item>
		</swiper>
		
		<!-- 底部导航栏 -->
		<BottomNav 
			:activeTab="bottomActiveTab"
			:unreadCount="unreadCount"
			@navChange="handleNavChange"
		/>
	</view>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import TopNav from '@/components/TopNav/TopNav.vue'
import VideoItem from '@/components/VideoItem/VideoItem.vue'
import ActionButtons from '@/components/ActionButtons/ActionButtons.vue'
import BottomNav from '@/components/BottomNav/BottomNav.vue'
import SideDrawer from '@/components/SideDrawer/SideDrawer.vue'

// 屏幕高度
const screenHeight = ref(0)

// 当前视频索引
const currentIndex = ref(0)

// 顶部标签
const activeTab = ref('recommend')

// 底部导航
const bottomActiveTab = ref('home')
const unreadCount = ref(6)

// 抽屉引用与用户信息
const sideDrawerRef = ref(null)
const user = ref({
	isLoggedIn: false,
	nickname: '',
	avatar: '',
	uid: ''
})

const STORAGE_USER_KEY = 'dy_user_state'

// 模拟视频数据
const videoList = ref([
    {
		id: 1,
		title: '人口只剩四亿!',
		subtitle: '不生孩子怎么破?',
        videoUrl: 'https://www.w3schools.com/html/mov_bbb.mp4', // 可播放示例视频
		cover: 'https://via.placeholder.com/750x1334/000000/FFFFFF?text=Video1',
		authorName: '张俊妮',
		authorTitle: '北京大学国家发展研究院副教授',
		authorAvatar: 'https://via.placeholder.com/96/0066CC/FFFFFF?text=ZJN',
		channelName: '太学TAIXUE',
		description: '我国的人口会',
		fullDescription: '张俊妮:人口只剩四亿!不生孩子怎么破?中国人口或骤降至4亿!大家都不愿意生孩子的原因是什么?这个问题该如何解决?',
		filmDate: '2025-09-24',
		filmLocation: '北京',
		likeCount: 189000,
		commentCount: 30000,
		favoriteCount: 43000,
		shareCount: 84000,
		isLiked: false,
		isFavorited: false,
		isFollowed: false,
		chapterText: '三章节要点'
	},
    {
		id: 2,
		title: '人工智能的未来',
		subtitle: 'AI将如何改变我们的生活?',
        videoUrl: 'https://media.w3.org/2010/05/sintel/trailer.mp4',
		cover: 'https://via.placeholder.com/750x1334/000000/FFFFFF?text=Video2',
		authorName: '李教授',
		authorTitle: '清华大学计算机系教授',
		authorAvatar: 'https://via.placeholder.com/96/FF6600/FFFFFF?text=LP',
		channelName: '科技前沿',
		description: '人工智能技术正在快速发展',
		fullDescription: '李教授:人工智能的未来在哪里?AI将如何改变我们的生活?从ChatGPT到自动驾驶，人工智能正在各个领域发挥重要作用。',
		filmDate: '2025-09-25',
		filmLocation: '北京',
		likeCount: 256000,
		commentCount: 45000,
		favoriteCount: 68000,
		shareCount: 120000,
		isLiked: false,
		isFavorited: false,
		isFollowed: false,
		chapterText: '三章节要点'
	},
    {
		id: 3,
		title: '健康生活新方式',
		subtitle: '如何保持身心健康?',
        videoUrl: 'https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4',
		cover: 'https://via.placeholder.com/750x1334/000000/FFFFFF?text=Video3',
		authorName: '王医生',
		authorTitle: '北京协和医院主任医师',
		authorAvatar: 'https://via.placeholder.com/96/00AA00/FFFFFF?text=WY',
		channelName: '健康生活',
		description: '健康的生活方式非常重要',
		fullDescription: '王医生:健康生活新方式，如何保持身心健康?合理的饮食、充足的睡眠、适量的运动，这些看似简单的生活习惯，却是保持健康的关键。',
		filmDate: '2025-09-26',
		filmLocation: '北京',
		likeCount: 178000,
		commentCount: 28000,
		favoriteCount: 52000,
		shareCount: 96000,
		isLiked: false,
		isFavorited: false,
		isFollowed: false,
		chapterText: '三章节要点'
	},
    {
		id: 4,
		title: '经济新趋势',
		subtitle: '未来十年的投资机会',
        videoUrl: 'https://media.w3.org/2010/05/bunny/trailer.mp4',
		cover: 'https://via.placeholder.com/750x1334/000000/FFFFFF?text=Video4',
		authorName: '赵分析师',
		authorTitle: '知名投资机构首席分析师',
		authorAvatar: 'https://via.placeholder.com/96/AA00AA/FFFFFF?text=ZF',
		channelName: '财经观察',
		description: '了解经济趋势很重要',
		fullDescription: '赵分析师:经济新趋势，未来十年的投资机会在哪里?从新能源到人工智能，从消费升级到数字化转型，这些领域都蕴藏着巨大的投资机会。',
		filmDate: '2025-09-27',
		filmLocation: '上海',
		likeCount: 234000,
		commentCount: 38000,
		favoriteCount: 61000,
		shareCount: 110000,
		isLiked: false,
		isFavorited: false,
		isFollowed: false,
		chapterText: '三章节要点'
	},
    {
		id: 5,
		title: '教育新理念',
		subtitle: '如何培养孩子的创造力?',
        videoUrl: 'https://media.w3.org/2010/05/video/movie_300.mp4',
		cover: 'https://via.placeholder.com/750x1334/000000/FFFFFF?text=Video5',
		authorName: '陈老师',
		authorTitle: '北京师范大学教育学教授',
		authorAvatar: 'https://via.placeholder.com/96/FF00FF/FFFFFF?text=CL',
		channelName: '教育之声',
		description: '培养创造力很重要',
		fullDescription: '陈老师:教育新理念，如何培养孩子的创造力?传统的填鸭式教育已经无法满足未来社会的需求，我们需要培养孩子的创新思维和解决问题的能力。',
		filmDate: '2025-09-28',
		filmLocation: '北京',
		likeCount: 198000,
		commentCount: 32000,
		favoriteCount: 49000,
		shareCount: 87000,
		isLiked: false,
		isFavorited: false,
		isFollowed: false,
		chapterText: '三章节要点'
	}
])

// 获取屏幕高度
const getScreenHeight = () => {
	const systemInfo = uni.getSystemInfoSync()
	screenHeight.value = systemInfo.windowHeight
}

// 滑动切换视频
const handleSwiperChange = (e) => {
	currentIndex.value = e.detail.current
	// 可以在这里添加视频播放统计等逻辑
	// TODO: 调用接口记录视频播放
	// api.recordVideoPlay(videoList.value[currentIndex.value].id)
}

// 顶部标签切换
const handleTabChange = (tab) => {
	activeTab.value = tab
	// TODO: 根据标签切换视频列表
	// api.getVideoListByTab(tab).then(res => {
	//   videoList.value = res.data
	//   currentIndex.value = 0
	// })
}

// 菜单点击
const handleMenuClick = () => {
	// 打开左侧抽屉（确保子组件已挂载）
	if (sideDrawerRef.value && typeof sideDrawerRef.value.open === 'function') {
		sideDrawerRef.value.open()
		return
	}
	
	nextTick(() => {
		if (sideDrawerRef.value && typeof sideDrawerRef.value.open === 'function') {
			sideDrawerRef.value.open()
		} else {
			// 兜底重试一次
			setTimeout(() => {
				if (sideDrawerRef.value && typeof sideDrawerRef.value.open === 'function') {
					sideDrawerRef.value.open()
				} else {
					uni.showToast({ title: '抽屉未就绪，请重试', icon: 'none' })
				}
			}, 50)
		}
	})
}

// 搜索点击
const handleSearchClick = () => {
	// TODO: 跳转到搜索页面
	uni.showToast({
		title: '打开搜索',
		icon: 'none'
	})
}

// 登录与退出
const safeGoLogin = () => {
	try {
		uni.navigateTo({ url: '/pages/login/login' })
	} catch (e1) {
		try {
			uni.redirectTo({ url: '/pages/login/login' })
		} catch (e2) {
			try {
				// H5 hash 路由兜底
				if (typeof location !== 'undefined') {
					location.hash = '#/pages/login/login'
				}
			} catch (e3) {}
		}
	}
}

const safeGoUpload = () => {
	try {
		uni.navigateTo({ url: '/pages/upload/upload' })
	} catch (e1) {
		try {
			uni.redirectTo({ url: '/pages/upload/upload' })
		} catch (e2) {
			try {
				if (typeof location !== 'undefined') {
					location.hash = '#/pages/upload/upload'
				}
			} catch (e3) {}
		}
	}
}

const handleLogin = () => {
	safeGoLogin()
}

const handleLogout = () => {
	user.value = {
		isLoggedIn: false,
		nickname: '',
		avatar: '',
		uid: ''
	}
	uni.showToast({ title: '已退出登录', icon: 'none' })
	sideDrawerRef.value && sideDrawerRef.value.close()
	try {
		uni.removeStorageSync(STORAGE_USER_KEY)
	} catch (e) {}
}

// 视频播放
const handleVideoPlay = (video) => {
	// TODO: 调用接口记录视频播放开始
	// api.videoPlayStart(video.id)
}

// 视频暂停
const handleVideoPause = (video) => {
	// TODO: 调用接口记录视频暂停
	// api.videoPlayPause(video.id)
}

// 弹幕点击
const handleDanmuClick = (video) => {
	// TODO: 打开弹幕设置
	uni.showToast({
		title: '弹幕设置',
		icon: 'none'
	})
}

// 章节相关已移除

// 作者声明点击
const handleStatementClick = (video) => {
	// TODO: 查看作者详情
	uni.showToast({
		title: '查看作者信息',
		icon: 'none'
	})
}

// 关注
const handleFollow = (video) => {
	// TODO: 调用关注接口
	// api.followUser(video.authorId).then(res => {
	//   if (res.success) {
	//     video.isFollowed = true
	//     uni.showToast({ title: '关注成功', icon: 'success' })
	//   }
	// })
	video.isFollowed = !video.isFollowed
	uni.showToast({
		title: video.isFollowed ? '关注成功' : '取消关注',
		icon: 'none'
	})
}

// 点赞
const handleLike = (video) => {
	// TODO: 调用点赞接口
	// api.likeVideo(video.id).then(res => {
	//   if (res.success) {
	//     video.isLiked = !video.isLiked
	//     video.likeCount += video.isLiked ? 1 : -1
	//   }
	// })
	video.isLiked = !video.isLiked
	video.likeCount += video.isLiked ? 1 : -1
}

// 评论
const handleComment = (video) => {
	// TODO: 打开评论页面
	// uni.navigateTo({
	//   url: `/pages/comments/comments?videoId=${video.id}`
	// })
	uni.showToast({
		title: '打开评论',
		icon: 'none'
	})
}

// 收藏
const handleFavorite = (video) => {
	// TODO: 调用收藏接口
	// api.favoriteVideo(video.id).then(res => {
	//   if (res.success) {
	//     video.isFavorited = !video.isFavorited
	//     video.favoriteCount += video.isFavorited ? 1 : -1
	//   }
	// })
	video.isFavorited = !video.isFavorited
	video.favoriteCount += video.isFavorited ? 1 : -1
}

// 分享
const handleShare = (video) => {
	// TODO: 调用分享接口
	// uni.share({
	//   provider: 'weixin',
	//   scene: 'WXSceneSession',
	//   type: 0,
	//   title: video.title,
	//   success: function (res) {
	//     api.shareVideo(video.id)
	//   }
	// })
	uni.showToast({
		title: '分享功能',
		icon: 'none'
	})
}

// 底部导航切换
const handleNavChange = (tab) => {
	if (tab === 'upload') {
		safeGoUpload()
		return
	}
	
	bottomActiveTab.value = tab
	
	// TODO: 根据tab跳转到对应页面
	// if (tab !== 'home') {
	//   uni.switchTab({
	//     url: `/pages/${tab}/${tab}`
	//   })
	// }
}

// 页面加载
onMounted(() => {
	getScreenHeight()
	
	// 监听屏幕旋转
	uni.onWindowResize(() => {
		getScreenHeight()
	})
	
	// 还原用户登录状态
	try {
		const cached = uni.getStorageSync(STORAGE_USER_KEY)
		if (cached && typeof cached === 'object') {
			user.value = cached
		}
	} catch (e) {}

	// 监听登录成功事件
	uni.$on('loginSuccess', (payload) => {
		if (payload && typeof payload === 'object') {
			user.value = payload
			// 登录成功后关闭抽屉
			sideDrawerRef.value && sideDrawerRef.value.close()
		}
	})
	
	// TODO: 加载视频列表
	// api.getVideoList().then(res => {
	//   videoList.value = res.data
	// })
})

onUnmounted(() => {
	uni.offWindowResize()
	uni.$off('loginSuccess')
})
</script>

<style scoped lang="scss">
.video-page {
	width: 100%;
	height: 100vh;
	background: #000;
	position: relative;
	overflow: hidden;
}

.video-swiper {
	width: 100%;
	height: 100%;
}

.swiper-item {
	width: 100%;
	height: 100%;
	position: relative;
}
</style>
